package org.csu.pet_store_back.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.csu.pet_store_back.common.CommonResponse;
import org.csu.pet_store_back.domain.Account;
import org.csu.pet_store_back.persistence.AccountMapper;
import org.csu.pet_store_back.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;

    /**
     * 登录逻辑返回
     * */
    public CommonResponse<Account> login(String username, String password) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",username).eq("password",password);
        queryWrapper.eq("is_admin",false);
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null){
            return CommonResponse.createForError("用户名或密码错误");
        } else{
            account.setPassword(null);
            return CommonResponse.createForSuccess("登录成功",account);
        }
    }

    /**
     * 注册逻辑返回
     * */
    public CommonResponse<Account> register(Account account) {
        account.setIsAdmin(false);
        accountMapper.insert(account);
        return CommonResponse.createForSuccess("注册成功",account);
    }

    /**
     * 修改逻辑返回
     * */
    public CommonResponse<Account> update(Account account) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",account.getUserid());
        Account account1 = accountMapper.selectOne(queryWrapper);
        if (account1 == null){
            return CommonResponse.createForError("用户名错误或不存在，修改失败！");
        } else {
            accountMapper.update(account,queryWrapper);
            account.setPassword(null);
            return CommonResponse.createForSuccess("修改成功",account);
        }
    }
}
